﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Decisions.HL7.Message;
using Decisions.HL7.Parser;

namespace Decisions.HL7.DataTypes
{
    [DataContract]
    public class Envelope
    {
        [DataMember]
        public int RawMessageCount { get; set; }

        private List<AbstractMessage> AllMessages = new List<AbstractMessage>();

        [DataMember]
        public int MessageCount
        {
            get
            {
                return AllMessages.Count;
            }
            set {  } // Read only.

        }

        [DataMember]
        public AbstractMessage[] HL7Messages {
            get {
                return AllMessages.ToArray();
            }
            set {
                AllMessages.Clear();
                AllMessages.AddRange(value);
            }
        }

        internal void AddMessage(AbstractMessage singleMessage)
        {
            AllMessages.Add(singleMessage);
        }

        internal void AddMessages(AbstractMessage[] messages) {
            AllMessages.AddRange(messages);
        }

        public override string ToString()
        {
            // Only Generate ER7 if we have messages
            if (HL7Messages == null || HL7Messages.Length == 0) return string.Empty;
            List<string> er7Messages = new List<string>();

            foreach (AbstractMessage eachMsg in HL7Messages) {
                er7Messages.Add(eachMsg.GetER7());
            }

            return string.Join(HL7ParserConstants.DEFAULT_MESSAGE_SEP, er7Messages.ToArray());
        }

        public string GetER7(HL7ParserOptions options)
        {
            // Only Generate ER7 if we have messages
            if (HL7Messages == null || HL7Messages.Length == 0) return string.Empty;
            List<string> er7Messages = new List<string>();

            foreach (AbstractMessage eachMsg in HL7Messages)
            {
                er7Messages.Add(eachMsg.GetER7(options));
            }

            return string.Join(HL7ParserConstants.DEFAULT_MESSAGE_SEP, er7Messages.ToArray());
        }

        [DataMember]
        public string WholeEnvelopeAsER7Text { get { return ToString(); } set { return; } }

        public bool HadParserErrors()
        {
            return HL7Messages.Any(m => m.HadParserError);
        }

        public string[] GetParserErrors()
        {
            return HL7Messages.SelectMany(m => m.ParserMessages).ToArray();
        }
    }
}
